<template>
  <view class="my-address-page">
    <view class="header">
      <view class="section-title">收货地址管理</view>
      <nut-button type="primary" class="add-address-btn" plain size="small" @tap="isEdit = !isEdit">{{ isEdit ? "完成" :
        "编辑" }}</nut-button>
    </view>

    <!-- 地址列表 -->
    <view scroll-y class="address-list" v-if="addressList.length > 0">
      <view v-for="address in addressList" :key="address.id" @tap="handleSelect(address)" class="address-item">
        <view class="address-content">
          <view class="user-info">
            <text class="name">{{ address.userName }}</text>
            <text class="phone">{{ address.phone }}</text>
            <nut-tag v-if="address.status == 1" type="primary" class="default-tag">默认</nut-tag>
          </view>
          <view class="address-detail">
            {{ address.address1 || "-" }} {{ address.address2 || "-" }}
          </view>
        </view>
        <view class="address-actions" v-if="isEdit">
          <nut-button size="small" @tap.stop="setDefaultConfirm(address)" plain class="def-btn"
            type="primary">设为默认</nut-button>
          <nut-button size="small" @tap.stop="showDeleteConfirm(address)" type="danger">
            <template #icon>
              <!-- <IconFont name="close" size="9"></IconFont> -->
              <IconFont font-class-name="iconfont" class-prefix="icon" name="shanchu" size="12" />
            </template>
            删除
          </nut-button>
          <nut-button size="small" @tap.stop="showEdit(address)" type="default">
            <template #icon>
              <!-- <Edit size="16"/> -->
              <IconFont name="edit" size="12"></IconFont>
            </template>
            编辑
          </nut-button>
        </view>
      </view>
    </view>

    <view class="empty-state" v-else>
      <nut-empty description="暂无收货地址">
        <template #image>
          <Location class="location-icon" />
        </template>
      </nut-empty>
      <view class="empty-hint">点击下方按钮添加新地址</view>
    </view>

    <view class="add-btn-container">
      <nut-button block type="primary" class="add-btn" @click="handleAddNew">
        <template #icon>
          <Add class="add-icon" />
        </template>
        添加新地址
      </nut-button>
    </view>

    <!-- 删除确认弹窗 -->
    <nut-popup v-model:visible="showDeleteModal" position="center" round>
      <view class="delete-modal">
        <view class="modal-header">
          <!-- <Warning class="warning-icon" /> -->
          <text class="modal-title">删除地址</text>
        </view>
        <view class="modal-content">
          确定要删除这个收货地址吗？删除后无法恢复
        </view>
        <view class="modal-actions">
          <nut-button plain type="primary" class="cancel-btn" @click="showDeleteModal = false">
            取消
          </nut-button>
          <nut-button type="primary" class="confirm-btn" @click="confirmDelete">
            确认删除
          </nut-button>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";
import {
  Add,
  // Delete,
  Edit,
  Location,
  // Warning
} from "@nutui/icons-vue-taro";
import Taro from "@tarojs/taro";
import http from "@/utils/http";

Taro.setNavigationBarTitle({
  title: "收货地址",
});

const isEdit = ref(false);

// 地址列表接口
// interface Address {
//   id: number;
//   name: string;
//   phone: string;
//   province: string;
//   city: string;
//   district: string;
//   detail: string;
//   isDefault: boolean;
// }

// 接口数据
// const addressList = ref<Address[]>([]);

// 地址列表模拟数据
const addressList = ref([
  {
    address1: "河北省,唐山市,路北区",
    address2: "味儿",
    id: 156,
    phone: "13455665544",
    status: 1,
    userId: 152,
    userName: "张三"
  },
  {
    address1: "河北省,唐山市,路北区",
    address2: "路北区",
    id: 157,
    phone: "13455665544",
    status: 0,
    userId: 153,
    userName: "李四"
  },
])

const showDeleteModal = ref(false);
const selectedAddress = ref<Address | null>(null);

// 更新设置默认地址
function setDefaultConfirm(address: Address) {
  console.log("设置默认地址:", address);
  http
    .postQuery("/api/user/updateAddress", {
      ...address,
      status: 1,
    })
    .then((res) => {
      console.log("设置默认地址成功", res);
      Taro.showToast({
        title: res.code == 0 ? '设置成功' : '设置失败',
        icon: "none",
      });
      getAddress();
    });
}

function showEdit(address: Address) {
  console.log("编辑地址:", address);
  Taro.navigateTo({
    url: `/pages-detail/addr/index?id=${address.id}`,
    events: {
      updates: (res) => {
        console.log("更新地址列表", res);
        getAddress();
      },
    },
  });
}

onMounted(() => {
  getAddress();
});

Taro.usePullDownRefresh(() => {
  getAddress();
  setTimeout(() => {
    Taro.stopPullDownRefresh();
  }, 1000);
});

// 获取列表数据
function getAddress() {
  http.postQuery("/api/user/getAddress", {}).then((res) => {
    console.log("地址列表", res);
    if (res?.data?.length) {
      addressList.value = res.data.map((i) => i.columns);
      selectedAddress.value = addressList.value[0];
    } else {
      addressList.value = [];
    }
  });
}
// 选择收货地址
const handleSelect = (address: Address) => {
  // 设置默认地址
  address.status = 1
  // 传递地址
  Taro.setStorageSync('address', {
    address: address
  });
  Taro.navigateBack({ delta: 1 });
};

const handleAddNew = () => {
  // console.log('添加新地址');
  Taro.navigateTo({
    url: "/pages-detail/addr/index",
    events: {
      updates: (res) => {
        console.log("更新地址列表", res);
        getAddress();
      },
    },
  });
};

const handleEdit = (address: Address) => {
  console.log("编辑地址:", address);
  // Taro.navigateTo({ url: `/pages-detail/addr/index?id=${address.id}&type=edit` });
};

const showDeleteConfirm = (address: Address) => {
  selectedAddress.value = address;
  showDeleteModal.value = true;
};

const confirmDelete = () => {
  if (selectedAddress.value) {
    http
      .postQuery("/api/user/delAddressById", {
        id: selectedAddress.value.id,
      })
      .then((res) => {
        console.log("删除地址成功", res);
        Taro.showToast({
          title: res.code == 0 ? res.data : "删除失败",
          icon: "none",
        });
        getAddress();
      });
    // const index = addressList.value.findIndex(
    //   (item) => item.id === selectedAddress.value!.id
    // );
    // if (index !== -1) {
    //   addressList.value.splice(index, 1);
    // }
  }
  showDeleteModal.value = false;
  selectedAddress.value = null;
};
</script>

<style lang="scss">
.my-address-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f7f8fa;

  .address-list {
    flex: 1;

    .address-item {
      background: #fff;
      border-radius: 16rpx;
      margin-bottom: 20rpx;
      padding: 30rpx;
      position: relative;

      .address-content {
        .user-info {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          margin-bottom: 16rpx;

          .name {
            font-size: 32rpx;
            font-weight: 500;
            margin-right: 20rpx;
          }

          .phone {
            font-size: 28rpx;
            color: #666;
            margin-right: 20rpx;
          }

          .default-tag {
            font-size: 24rpx;
            padding: 4rpx 12rpx;
            border-radius: 8rpx;
          }
        }

        .address-detail {
          font-size: 28rpx;
          line-height: 1.5;
          color: #333;
        }
      }
    }
  }

  .empty-state {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 60rpx 32rpx;

    .location-icon {
      width: 160rpx;
      height: 160rpx;
      color: #ddd;
      margin-bottom: 32rpx;
    }

    .empty-hint {
      font-size: 28rpx;
      color: #999;
      text-align: center;
    }
  }

  .add-btn-container {
    padding: 24rpx 32rpx;
    background: #fff;
    border-top: 1rpx solid #eee;

    .add-btn {
      height: 88rpx;
      font-size: 32rpx;
      border-radius: 44rpx;

      .add-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 12rpx;
      }
    }
  }

  .delete-modal {
    padding: 32rpx;
    width: 560rpx;

    .modal-header {
      text-align: center;
      margin-bottom: 24rpx;

      .modal-title {
        font-size: 32rpx;
        font-weight: 500;
      }
    }

    .modal-content {
      font-size: 28rpx;
      color: #666;
      text-align: center;
      margin-bottom: 32rpx;
      line-height: 1.5;
    }

    .modal-actions {
      display: flex;
      justify-content: space-between;
      gap: 20rpx;

      .cancel-btn,
      .confirm-btn {
        flex: 1;
        height: 80rpx;
        font-size: 30rpx;
        border-radius: 40rpx;
      }
    }
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 32rpx;
  background-color: #f7f8fa;
}

.address-actions {
  display: flex;
  margin-top: 8rpx;
  gap: 12rpx;
}

.def-btn {
  margin-right: auto;
}
</style>
